import React from 'react';
import { InputNumber } from 'antd';
import { InputFromToProps, InputFromToState } from '../data';

/**
 * cron时间表达式生成器-秒面板
 * 属性如下：
 */
class InputFromTo extends React.PureComponent<InputFromToProps, InputFromToState> {

  state: InputFromToState = {
    from: 0,
    to: 0
  }

  /**
   * 静态函数，根据新传入的props来映射到state。
   * 该函数必须有返回值。当props传入的内容不需要影响state，就必须返回一个null
   */
  static getDerivedStateFromProps(nextProps: InputFromToProps, prevState: InputFromToState) {
    const { disabled, value } = nextProps;
    if (disabled) {
      return {
        from: 0,
        to: 0
      };
    } else {
      if (value) {
        const [from, to] = value.split('-').map((v) => parseInt(v, 10));
        return {
          from,
          to
        }
      }
    }
    return null;
  }

  onChangeFrom = (value: number | null) => {
    const { onChange } = this.props;
    const { to } = this.state;
    if (value) {
      this.setState({
        from: value
      });
      if (onChange) {
        onChange(`${value || 0}-${to}`);
      }
    }
  }

  onChangeTo = (value: number | null) => {
    const { onChange } = this.props;
    const { from } = this.state;
    if (value) {
      this.setState({
        to: value
      });
      if (onChange) {
        onChange(`${from || 0}-${value}`);
      }
    }
  }

  render() {
    const { disabled } = this.props;
    let { from, to } = this.state;

    return (
      <React.Fragment>
        周期从&nbsp;
        <InputNumber
            disabled={disabled}
            min={0}
            max={59}
            value={from as number}
            onChange={this.onChangeFrom}
            style={{ width: 100 }}
        />
        &nbsp;-&nbsp;
        <InputNumber
            disabled={disabled}
            min={0}
            max={59}
            value={to as number}
            onChange={this.onChangeTo}
            style={{ width: 100 }}
        />
        &nbsp;秒，每秒执行一次
      </React.Fragment>
    );
  }
}

export default InputFromTo;